package ae.pcfc.cldos.online.web.services.fnp.provider;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;

import ae.pcfc.cldos.online.fnp.service.client.vo.FNPParameterVO;
import ae.pcfc.cldos.online.web.services.fnp.FnpParametersCheckService;

/**
 * 
 * @author arosa
 *
 */
@Service
public class FnpParametersCheskServiceImpl implements FnpParametersCheckService {
	
	private static final String __MAPPING_STATIC = "STATIC";
	
	private static final String __REQUEST_PARAM_PREFIX = "FNPPAR_";
	
	
	public List<FNPParameterVO> feelParamsAndGetNotFeeled(HttpServletRequest request, List<FNPParameterVO> allParams){
		
		List<FNPParameterVO> notCompleted = new ArrayList<FNPParameterVO>();
		if(allParams!=null){
			for(FNPParameterVO fnpParameterVO : allParams){
				String mapping = fnpParameterVO.getMapping();
				if(mapping!=null && mapping.equalsIgnoreCase(__MAPPING_STATIC)){
					fnpParameterVO.setDisplayFlag(false);
					continue;
				}else if(mapping!=null && !mapping.isEmpty()){
					String reqValue = request.getParameter(mapping);
					if(reqValue!=null && !reqValue.isEmpty()){
						fnpParameterVO.setValue(reqValue);
						fnpParameterVO.setDisplayFlag(false);
						continue;
					}
				}
				
				fnpParameterVO.setDisplayFlag(true);
				String reqParamName = convertParamNameToRequestParamName(fnpParameterVO.getName());
				String value = request.getParameter(reqParamName);
				if(value!=null && !value.isEmpty()){
					fnpParameterVO.setValue(value);
					fnpParameterVO.setMapping(reqParamName);
				} else {
					notCompleted.add(fnpParameterVO);
				}
			}
		}
		return notCompleted;
	}
	
	public List<FNPParameterVO> getRequiredParams(HttpServletRequest request, List<FNPParameterVO> allParams){
		
		List<FNPParameterVO> required = new ArrayList<FNPParameterVO>();
		
		for(FNPParameterVO fnpParameterVO : allParams){
			String mapping = fnpParameterVO.getMapping();
			if(mapping!=null && mapping.equalsIgnoreCase(__MAPPING_STATIC)){
				continue;
			}else if(mapping!=null && !mapping.isEmpty()){
				String reqValue = request.getParameter(mapping);
				if(reqValue!=null && !reqValue.isEmpty()){
					continue;
				}
			}
			fnpParameterVO.setMapping(convertParamNameToRequestParamName(fnpParameterVO.getName()));
			required.add(fnpParameterVO);
		}
		return required;
	}
	
	private String convertParamNameToRequestParamName(String paramName){
		return __REQUEST_PARAM_PREFIX+spacesToUnderscores(paramName);
	}
	
	private String spacesToUnderscores(String in){
		return in.replaceAll(" ", "_");
	}
}
